import React, { useEffect, useState } from 'react';
import { Tabs } from 'antd';
import { open } from '@tauri-apps/plugin-dialog';

import { getLocalStorageObjectWithDefault, getLocalStorageWithDefault, setLocalStorage } from '../../utils';
import { RightSquareFilled } from '@ant-design/icons';

export const OPENED_FILES_KEY = '$G01_OPENED_FILES_';

export const OPENED_ACTIVE_FILE_KEY = '$G01_OPENED_ACTIVE_FILE_';

export interface FileItem {
    name: string;
    path: string;
}

export type AppendCallback = (fileItem: FileItem | null, options?: { [key: string]: any }) => void;

export interface FileTabsProps {
    category: string;
    extentions?: string;
    hideAdd?: boolean;
    tabMaxWidth?: number;
    tabBarExtraContent?: (callback: AppendCallback) => { left?: React.ReactNode, right?: React.ReactNode };
    onAdd?: () => Promise<FileItem | null>;
    onChange: (key: FileItem | null) => Promise<void>;
};


export const FileTabs: React.FC<FileTabsProps> = (props: FileTabsProps) => {

    // const [loading, setLoading] = useState<boolean>(false);

    const [data, setData] = useState<Array<FileItem>>([]);

    const [activeKey, setActiveKey] = useState<string | undefined>(undefined);

    const writeActiveKey = (category: string, activeKey: string) => {
        setLocalStorage(OPENED_ACTIVE_FILE_KEY + category, activeKey);
    };

    const getItemByKey = (data: Array<FileItem>, key: string): FileItem | null => {
        if (!data || data.length <= 0) {
            return null;
        }
        let index = parseInt(key);
        if (data.length > index) {
            return data[index];
        }
        // let res = data.filter(item => item.path === key);
        // if (res && res.length > 0) {
        //     return res[0];
        // }
        return null;
    };

    const getItemKeyByPath = (data: Array<FileItem>, path: string): number => {
        if (!data || data.length <= 0) {
            return -1;
        }
        for (let i = 0; i < data.length; i++) {
            if (data[i].path === path) {
                return i;
            }
        }
        return -1;
    };

    const readData = (category: string, activeKey: string | undefined) => {
        //读取数据
        let data: Array<FileItem> = getLocalStorageObjectWithDefault(OPENED_FILES_KEY + category, []);
        setData(data);
        //读取默认的选中
        let activeKey1 = getLocalStorageWithDefault(OPENED_ACTIVE_FILE_KEY + category, activeKey);
        if (activeKey1 !== activeKey) {
            //不同
            let item = getItemByKey(data, activeKey1);
            if (item && item.path) {
                setActiveKey(activeKey1);
                return;
            }
        }
        if (activeKey === undefined && data.length > 0) {
            setActiveKey('0');
            writeActiveKey(category, '0');
        }
    };

    const writeData = (category: string, data: Array<FileItem>) => {
        setLocalStorage(OPENED_FILES_KEY + category, JSON.stringify(data));
    };

    const removeItemByKey = (data: Array<FileItem>, key: string): Array<FileItem> => {
        if (!data || data.length <= 0) {
            return [];
        }
        let res = data.filter((item, index) => index + '' !== key);
        if (res && res.length >= 0) {
            return res;
        }
        return data;
    };

    useEffect(() => {
        if (props.category && props.category != '') {
            readData(props.category, activeKey);
        }
    }, [props.category]);


    useEffect(() => {
        if (!activeKey) {
            props.onChange(null);
            return;
        };
        let item = getItemByKey(data, activeKey);
        if (item && item.path) {
            props.onChange(item);
            return;
        }
    }, [activeKey]);

    return (
        <Tabs
            data-tauri-drag-region
            hideAdd={props.hideAdd}
            tabPosition={'top'}
            size={'small'}
            tabBarGutter={2}
            tabBarStyle={{
                margin: 0,
            }}
            tabBarExtraContent={props.tabBarExtraContent ? props.tabBarExtraContent((fileItem, options): void => {
                //追加
                try {
                    if (fileItem != null) {
                        //
                        let newData = data.concat([fileItem]);
                        setData(newData);
                        setActiveKey((newData.length - 1) + '');
                        writeData(props.category, newData);
                    }
                } catch (err) {
                    console.log(err);
                }
            }) : undefined}
            onChange={(key: string) => {
                if (activeKey != key) {
                    let item = getItemByKey(data, key);
                    if (item) {
                        setActiveKey(key);
                        writeActiveKey(props.category, key);
                    }
                }
            }}
            activeKey={activeKey}
            type="editable-card"
            onEdit={async (targetKey: any, action: 'add' | 'remove') => {
                if (action === 'add') {
                    let item: FileItem | null = null;
                    try {
                        //
                        if (props.onAdd) {
                            item = await props.onAdd();
                        } else {
                            //默认打开文件
                            const file: any = await open({
                                multiple: false,
                                directory: false,
                            }) as any;
                            if (!file) {
                                return;
                            }
                            console.log(file, file.path);
                            item = {
                                name: file,
                                path: file,
                            }
                        }
                    } catch (err) {
                        console.log(err);
                    }
                    if (item != null) {
                        //判断item是否存在
                        let index = getItemKeyByPath(data, item.path);
                        if (index >= 0) {
                            //
                            setActiveKey(index + '');
                        } else {
                            let newData = data.concat([item]);
                            setData(newData);
                            setActiveKey((newData.length - 1) + '');
                            writeData(props.category, newData);
                        }
                    }
                } else {
                    let newData = removeItemByKey(data, targetKey);
                    setData(newData);
                    writeData(props.category, newData);
                    if (newData && newData.length > 0) {
                        setActiveKey('0');
                    } else {
                        setActiveKey(undefined);
                    }
                }
            }}
            items={data.map((item, index) => {
                //antd使用path做key，无法显示更多的按钮
                return {
                    label: item.name,
                    key: index + ''
                }
            })}
        >
        </Tabs>
    );
}

export default FileTabs;